const jsonServer = require('json-server');//在node里面使用json-server包
const json_server = require('./json-server.json');
console.log("json_server=",json_server);
//console.log("json_server_routes=",json_server.routes);
const json_server_routes = require('./' + json_server.routes);
//console.log("json_server_routes=",json_server_routes);
const path = require('path');
const Mock = require('mockjs');
const _ = require('underscore')
const fs = require('fs')
let devApi='/dev-api';//定义路由根别名

//console.log("jsonServer=",jsonServer);

//创建服务器
const server = jsonServer.create();//创建jsonserver 服务对象
//console.log("jsonServer.create()=",server);

// console.log("jsonServer.defaults()=",jsonServer.defaults({
//   static:path.join(__dirname, '/public'),//静态资源托管
// }));
//配置jsonserver服务器 中间件
server.use(jsonServer.defaults({
  static:path.join(__dirname, '/public'),//静态资源托管
}));
server.use(jsonServer.bodyParser);//抓取body数据使用json-server中间件
//console.log("jsonServer.bodyParser=",jsonServer.bodyParser);


//响应
// server.use((request, res, next) => {//可选 统一修改请求方式
//   console.log("server.use")
//   // request.method = 'GET';
//   next();
// });
server.use((req, res, next) => {
  console.log("server.use=",req.method)
  if (req.method === 'POST') {
    req.body.createdAt = Date.now()
  }
  next()
})
//登录注册校验
let mr = Mock.Random;//提取mock的随机对象
server.get(devApi+'/user/login', (req, res) => {
  // console.log(req.query, req.body);//抓取提交过来的query和body
  let username=req.query.username;
  let password=req.query.password;
  (username === 'admin') ?
  res.jsonp({
    "err": 0,
    "msg": "登录成功",
    "data": {
      "follow": mr.integer(1,5),
      "fans": mr.integer(1,5),
      "nikename": mr.cname(),
      "icon": mr.image('20x20',mr.color(),mr.cword(1)),
      "time": mr.integer(13,13)
    }
  }) : (username === 'editor') ?
  res.jsonp({
    "err": 0,
    "msg": "登录成功",
    "data": {
      "follow": mr.integer(1,5),
      "fans": mr.integer(1,5),
      "nikename": mr.cname(),
      "icon": mr.image('20x20',mr.color(),mr.cword(1)),
      "time": mr.integer(13,13)
    }
  }) :
  res.jsonp({
    "err": 1,
    "msg": "登录失败",
  })
});
server.post(devApi+'/user/login', (req, res) => {
  console.log('/user/login=', req.query, req.body);//抓取提交过来的query和body
  console.log('/user/login=', req.socket);//抓取提交过来的query和body
  let username=req.body.username;
  let password=req.body.password;
  //(username === 'aa' && password === 'aa123')?
  (username === 'admin') ?
    res.jsonp({
      "err": 0,
      "msg": "登录成功",
      "data": {
        "follow": mr.integer(1,5),
        "fans": mr.integer(1,5),
        "nikename": mr.cname(),
        "icon": mr.image('20x20',mr.color(),mr.cword(1)),
        "time": mr.integer(13,13)
      }
    }) : (username === 'editor') ?
    res.jsonp({
      "err": 0,
      "msg": "登录成功",
      "data": {
        "follow": mr.integer(1,5),
        "fans": mr.integer(1,5),
        "nikename": mr.cname(),
        "icon": mr.image('20x20',mr.color(),mr.cword(1)),
        "time": mr.integer(13,13)
      }
    }) :
    res.jsonp({
      "err": 1,
      "msg": "登录失败",
    })
});
server.post(devApi+'/reg', (req, res) => {
  let username=req.body.username;
  (username !== 'aa') ?
    res.jsonp({
      "err": 0,
      "msg": "注册成功",
      "data": {
        "follow": mr.integer(0,0),
        "fans": mr.integer(0,0),
        "nikename": mr.cname(),
        "icon": mr.image('20x20',mr.color(),mr.cword(1)),
        "time": mr.integer(13,13)
      }
    }) :
    res.jsonp({
      "err": 1,
      "msg": "注册失败",
    })

});


///////////////////////////////////////////////////////////////////////////////////////////////////////////////

// // 支持加载多个db json文件
// const mockDir = path.join(__dirname, 'data')
// const base = {}
// const files = fs.readdirSync(mockDir)
// files.forEach(function (file) {
//   _.extend(base, require(path.resolve(mockDir, file)))
// })
// console.log("router=",base);
// const router = jsonServer.router(base)
// console.log("router=",router);

// router.render = (req, res) => {//自定义返回结构
//   let len = Object.keys(res.locals.data).length; //判断数据是不是空数组和空对象
//   // console.log(len);
//   setTimeout(()=>{//模拟服务器延时
//     res.jsonp({
//       err: len !== 0 ? 0 : 1,
//       msg: len !== 0 ? '成功' : '失败',
//       data: res.locals.data
//     })
//   },1000)

//   // res.jsonp(res.locals.data)

// };

///////////////////////////////////////////////////////////////////////////////////////////////////////////////


server.use(router);//路由响应










// json_server_routes[devApi+"/*"] = "/$1"
//console.log("json_server_routes=",json_server_routes);
server.use(jsonServer.rewriter(
  //json_server_routes
  {//路由自定义别名
  //[devApi+"/*"]: "/$1",
  '/api/*': '/$1',

  // "/product\\?dataName=:dataName": "/:dataName",
  // "/banner\\?dataName=:dataName": "/:dataName",
  // "/detail\\?dataName=:dataName&id=:id": "/:dataName/:id",

  // "/product/del\\?dataName=:dataName&id=:id": "/:dataName/:id",
  // "/product/add\\?dataName=:dataName": "/:dataName",
  // "/product/check\\?dataName=:dataName&id=:id": "/:dataName/:id"
  }
));




//开启jsonserver服务
server.listen(json_server.port, () => {
  console.log('mock server is running')
});
